package com.lupus.common;

import java.util.*;
import javax.servlet.http.HttpServletRequest;

public final class ResourceFactory {
	private static String propertyFile = "com/lupus/config/i18n";
	private static HashMap<String,ResourceBundle> localeMap = new HashMap<String,ResourceBundle>();
	
	public static String getLocalString(String key,String language){
		ResourceBundle resourceBundle = localeMap.get(language);
		if(resourceBundle == null){
			resourceBundle = ResourceBundle.getBundle(propertyFile,new Locale(language));
			localeMap.put(language,resourceBundle);
		}
		if(resourceBundle!=null&&key!=null){
			try{
				key = resourceBundle.getString(key);
			}catch(RuntimeException e){
				System.out.println("can't find resource for key: "+key);
			}
		}
		return key;
	}
	
	public static Map<String,String> getLocalUIStringMap(String language){
		Map<String,String> tempMap = new HashMap<String,String>();
		ResourceBundle resourceBundle = ResourceBundle.getBundle(propertyFile,new Locale(language));
		String key = null;
		if(resourceBundle!=null){
			try{
				Iterator<String> it = resourceBundle.keySet().iterator();
				while(it.hasNext()){
					key = it.next();
					if(key.startsWith("common.")){
						tempMap.put(key,resourceBundle.getString(key));
					}
				}
			}catch(Exception e){
				System.out.println("can't find resource for key: "+key);
			}
		}
		return tempMap;
	}
	
	public static String getLocalString(String key,Map<String,Object> actionMap){
		return getLocalString(key,(String)actionMap.get("localLanguage"));
	}
	
	public static String getLocalString(String key,HttpServletRequest request){
		return getLocalString(key,request.getLocale().getLanguage());
	}
}
